package com.ruoyi.project.er.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.PaeaConstants;
import com.ruoyi.common.enums.PaeaUserRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.er.domain.*;
import com.ruoyi.project.er.enums.PaeaErrorAcqiredStatus;
import com.ruoyi.project.er.enums.PaeaErrorReplyStatus;
import com.ruoyi.project.er.enums.PaeaErrorState;
import com.ruoyi.project.er.enums.PaeaErrorStatus;
import com.ruoyi.project.er.mapper.PaeaErErrorMapper;
import com.ruoyi.project.er.mapper.PaeaErErrorPointRelMapper;
import com.ruoyi.project.er.model.PaeaErErrorProcessVo;
import com.ruoyi.project.er.model.PaeaErErrorVo;
import com.ruoyi.project.er.service.*;
import com.ruoyi.project.system.parawork.domain.PaeaTaskLimitPara;
import com.ruoyi.project.system.parawork.service.IPaeaTaskLimitParaService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.tool.DateTimeUtil;
import com.ruoyi.project.wf.domain.*;
import com.ruoyi.project.wf.model.WorkitemSubmitDataWrapper;
import com.ruoyi.project.wf.service.IWfProcessActRoleRelService;
import com.ruoyi.project.wf.service.IWfProcessActService;
import com.ruoyi.project.wf.service.IWfProcessInstService;
import com.ruoyi.project.wf.service.IWfWorkItemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 督办查询Service业务层处理
 *
 * @author XQ.XU
 * @date 2020-03-22
 */
@Service
public class PaeaErErrorProcessServiceImpl extends ServiceImpl<PaeaErErrorMapper, PaeaErError> implements IPaeaErErrorProcessService
{
    @Resource
    private PaeaErErrorMapper paeaErErrorMapper;
    @Resource
    private PaeaErErrorPointRelMapper paeaErErrorPointRelMapper;
    @Resource
    private IPaeaErErrorPointRelService paeaErErrorPointRelService;
    @Resource
    private IPaeaErPointService paeaErPointService;
    @Resource
    private IPaeaErTypeService paeaErTypeService;
    @Resource
    private IWfProcessInstService wfProcessInstService;
    @Resource
    private IWfWorkItemService wfWorkItemService;
    @Resource
    private IWfProcessActService wfProcessActService;
    @Resource
    private IPaeaErErrorInstRelService paeaErErrorInstRelService;
    @Resource
    private IWfProcessActRoleRelService wfProcessActRoleRelService;
    @Resource
    private IPaeaErTypePointRelService paeaErTypePointRelService;
    @Resource
    private IPaeaErGradeService paeaErGradeService;
    @Resource
    private IPaeaTaskLimitParaService paeaTaskLimitParaService;


    @Override
    public int processError(PaeaErError paeaErError) {
        return 0;
    }

    @Override
    public List<PaeaErError> queryToDoList(PaeaErErrorVo vo) {


        vo.setCurUserId(ShiroUtils.getUserId());
        User u=ShiroUtils.getSysUser();
        vo.setCurRoleId(ShiroUtils.getSysUser().getRoles().get(0).getRoleId());

        return paeaErErrorMapper.queryToDoList(vo);
    }
    /**
     * 流程提交
     * @param vo
     * @return
     */
    public int submitWorkFlow(PaeaErErrorProcessVo vo) {
        String roleCode = ShiroUtils.getSysUser().getRoleId();
        // 差错id
        String errId =vo.getId();
        PaeaErError paeaErError = this.getById(errId);
        // 当前id
        String currentItemId =paeaErError.getCurWorkitemId();
        // 下一步id
        //TODO://页面需封装
        String nextItemId = vo.getNextWorkItemId();
        // 意见
        String remark =vo.getReplyComments();
        //整改意见、复核员才有权限去修改整改意见
        /*String auSuggest = rtool.getStringParameter("auSuggestUpdate");
        String judgeValue = rtool.getStringParameter("judgeValue");
        String tellerStr = rtool.getStringParameter("tellerStr");
        String errorReasonTypeLevel1 = rtool.getStringParameter("errorReasonTypeLevel1");
        String paeaErPoints = rtool.getStringParameter("paeaErPoints");
        int riskLevel = rtool.getIntParameter("riskLevel");
        String riskAccordingRemark = rtool.getStringParameter("riskAccordingRemark");
        int correctFlag=rtool.getIntParameter("correctFlag");
        String correctMethod=rtool.getStringParameter("impMessures");*/





            // 更新交易柜员信息
            if(!vo.getTellerId().equals(paeaErError.getTellerId())){
                paeaErError.setTellerId(vo.getTellerId());
            }
            // 修改差错状态(差错回复状态)
            changeErrStatus(roleCode, paeaErError);
            if("差错管理岗".equals(paeaErError.getErrState()) ){
                // update by wei.zhang 甘肃银行所有的差错都要定风险。所以暂时注释
				  /*if (roleCode.contains(PaeaUserRole.运行监控中心.getRoleCode())) {
				if (PaeaErrorRootType.重点监控差错2.getName().equals(erError.getErrTitle())
						|| PaeaErrorRootType.风险预警差错3.getName().equals(erError.getErrTitle())
						|| PaeaErrorRootType.补录预警差错4.getName().equals(erError.getErrTitle())) {*/
                // 更新整改信息
                paeaErError.setAuditSuggest(paeaErError.getAuditSuggest());
                /* 修改差错点
                if(null!=paeaErPoints && !"".equals(paeaErPoints)){
                    serviceErrorRegisterImpl.changeErrorPoint(smUser, paeaErPoints.split(","), erError);
                    PaeaErType paeaErType =service1ImpAuditImpl.queryMaxPaeaErType(paeaErPoints.split(","),PaeaErrorRootType.getCodeByName(erError.getErrTitle())); //差错的级别
                    if(null==paeaErType){
                        return AjaxTool.returnAjaxResponse(response, "1-不允许跨类型调整差错点,请重新选择");
                    }
                    paeaErError.setErrTypeId(paeaErType.getId());
                    riskLevel=Integer.parseInt(paeaErType.getCode().substring(3));
                    erError.setErrorGrade(riskLevel);
                }*/
                /*风险等级
                double riskScore = 0.00;
                if (riskLevel != 0) {
                    judgeValue="1";
                    riskScore = RiskLevel.getErrorTypeScore(riskLevel + "",servicePaeaErrorGradeValueImpl);
                }
                //add by wei.zhang 归档时
                paeaErError.setRiskLevel(riskLevel);
                paeaErError.setRiskScore(riskScore);
                paeaErError.setRiskAccordingRemark(riskAccordingRemark);
                paeaErError.setRiskOper(smUser.getUserCode());
                paeaErError.setRiskDate(new java.sql.Date(System.currentTimeMillis()));
                paeaErError.setCorrectFlag(vo.getCorrectFlag());
                this.servicePaeaErErrorImpl.updatePaeaErError(paeaErError);
               //recordWorkLog(servicePaeaReportBusinessImpl, smUser,riskLevel == 1 ? 1 : 0, riskLevel == 2 ? 1 : 0,riskLevel == 3 ? 1 : 0, riskLevel == 4 ? 1 : 0,riskLevel == 5 ? 1 : 0);
                */
            }

            //}

            //风险预警、网点回复状态时记录风险动因、整改措施。
            /*
            if PaeaUserRole.is网点回复人(roleCode)||roleCode.contains(PaeaUserRole.分行运营主任.getRoleCode())) {
                if (PaeaErrorRootType.风险预警差错3.getName().equals(erError.getErrTitle())) {
                    paeaErError.setReasonLevel1(errorReasonTypeLevel1);
                    paeaErError.setCorrectMethod(correctMethod);
                    remark=remark+""+correctMethod;
                    this.servicePaeaErErrorImpl.updatePaeaErError(erError);
                }
            }*/
            WfWorkItem nextWorkitem = submitErrorProcess(paeaErError, vo);
            return 0;
        }
        public WfWorkItem submitErrorProcess( PaeaErError paeaErError,PaeaErErrorProcessVo vo) {

            // 提交工作项
            WorkitemSubmitDataWrapper workitemResultDataWrapper = new WorkitemSubmitDataWrapper();
            workitemResultDataWrapper.parameterName_valueMap.put("remarkValue",vo.getReplyComments());
            workitemResultDataWrapper.parameterName_valueMap.put("judgeValue",vo.getAcquiredStatus());
            workitemResultDataWrapper.parameterName_valueMap.put("nextWfProcessActId", vo.getNextWorkItemId());
            WfWorkItem wfWorkItem = wfWorkItemService.submitWfWorkItem(vo.getCurWorkitemId(), workitemResultDataWrapper, paeaErError.getTrDate());
            //PaeaReportError paeaReportError = null;
            paeaErError.setReplyComments(vo.getReplyComments());

            if (wfWorkItem == null || "end".equals(wfWorkItem.getCode())) {
                // 流程结束
                //int value = Integer.valueOf(judgeValue);
               // paeaErError.setErrStatus(value);
                //流程结束时对整改情况进行写库操作
                paeaErError.setCorrectFlag(vo.getCorrectFlag());
                /**
                 * 确认差错：1、根据差错严重程度，生成差错书或工作底稿 2、直接走监管辅助流程，,并修改差错状态
                 */
                //if (1 == value) {
                if (1 == 2) {
                    paeaErError.setErrStatus(PaeaErrorStatus.Certified.getValue());
                    paeaErError.setErrState(PaeaErrorStatus.Certified.getName());
                    //paeaReportError = this.createPaeaReportError(paeaErError, true);

    //				WtCheckPaper wtCheckPaper = this.serviceWtCheckPaperImpl.createWtcheckPaperForErr(paeaErError, smUser);
    //				if (wtCheckPaper.getCheckType().equals(WtCheckPaperCheckType.工作底稿.getValue())) {// 生成工作底稿的，需要走流程
    //					this.serviceWtCheckProcessImpl.registerWtNormalCheck(wtCheckPaper.getId(), smUser,WtCheckProcessType.日常检查工作底稿.getCode(), paeaErError.getTrDate());
    //				}
                    //paeaErError.setCorrectFlag(1);// 已做监管检查(correctFlag=1)


                } else {
                    paeaErError.setErrStatus(PaeaErrorStatus.Finished.getValue());
                    paeaErError.setErrState(PaeaErrorStatus.Finished.getName());
                    //paeaReportError = this.createPaeaReportError(paeaErError, false);
                }

                paeaErError.setCurRoleId(null);
                paeaErError.setResponsibleOper("-1");
                paeaErError.setAcquiredTime(null);
                paeaErError.setCurWorkitemId(null);
                paeaErError.setAcquiredStatus(PaeaErrorAcqiredStatus.未获取.getValue());
               // this.servicePaeaReportErrorImpl.writeStatPaeaReportError(paeaReportError);
            }
            // add by wei.zhang 当节点回到开始状态的时候将状态更新为登记未发布
            else if("start".equals(wfWorkItem.getCode())){
                paeaErError.setErrStatus(PaeaErrorStatus.Registered.getValue());
                paeaErError.setErrState(PaeaErrorStatus.Registered.getName());
                //paeaErError.setCurWorkitemId(wfWorkItem.getId());
                paeaErError.setCurRoleId(null);
                paeaErError.setResponsibleOper("-1");
                paeaErError.setAcquiredStatus(null);
                paeaErError.setAcquiredTime(null);
                paeaErError.setCurWorkitemId(null);
                paeaErError.setAcquiredStatus(PaeaErrorAcqiredStatus.未获取.getValue());
            }else {
                String previouState = paeaErError.getErrState();
                paeaErError.setErrState(wfWorkItem.getName());
                //add by wei.zhang  流程创建人是空角色实现无法进入for循环，这里手动重置
                if("流程创建人".equals(paeaErError.getErrState())){
                    paeaErError.setCurRoleId("");
                    paeaErError.setResponsibleOper("-1");
                    paeaErError.setExclusiveOper("-1");
                    paeaErError.setAcquiredTime(null);
                    paeaErError.setAcquiredStatus(PaeaErrorAcqiredStatus.未获取.getValue());
                    paeaErError.setCurWorkitemId(wfWorkItem.getId());
                }else{
                    WfProcessAct wfProcessAct =wfProcessActService.selectWfProcessActById(wfWorkItem.getId());
                    for (WfProcessActRoleRel rel : wfProcessAct.getWfProcessActRoleRelsByProcActId()) {
                        paeaErError.setCurRoleId(rel.getRoleCode());
                        paeaErError.setResponsibleOper("-1");
                        paeaErError.setExclusiveOper("-1");
                        paeaErError.setAcquiredTime(null);
                        paeaErError.setAcquiredStatus(PaeaErrorAcqiredStatus.未获取.getValue());
                        paeaErError.setCurWorkitemId(wfWorkItem.getId());
                        break;
                    }
                }

                if (PaeaErrorState.业务主管审核.getCode().equals(paeaErError.getErrState())) {
                    paeaErError.setExclusiveOper(ShiroUtils.getUserId());// 因为有操作员同时兼任监管主管以及监管员两种角色,故需排除掉本人
                    paeaErError.setAuditOrg(ShiroUtils.getSysUser().getDeptId());// 因为存在省行监管员直接给网点下督办的情况,所以审核机构不能根据差错所属机构,而应根据监管员所属机构确定
                }
                // paeaReportError = this.createPaeaReportError(paeaErError);
            }

            // 更新差错状态
            this.saveOrUpdate(paeaErError);

            return wfWorkItem;
        }
        /**
         * 如果当前角色是会计主管，增加回复状态
         *
         * @说明ReplyFlag:按时处理1、超期已处理2、
         * @param roleCode
         *            当前用户角色
         * @param paeaErError
         *            差错ID
         */
         void changeErrStatus(String roleCode,PaeaErError paeaErError) {
            if (paeaErError.getReplyFlag() == null || paeaErError.getReplyFlag() == PaeaErrorReplyStatus.未回复.getValue() || paeaErError.getReplyFlag() == PaeaErrorReplyStatus.超期未回复.getValue()) {
                if (PaeaUserRole.is网点回复人(roleCode)) {
                    PaeaTaskLimitPara para = new PaeaTaskLimitPara();
                    para.setCode(PaeaConstants.ERROR);
                    PaeaTaskLimitPara paeaTaskLimitPara=paeaTaskLimitParaService.selectPaeaTaskLimitParaList(para).get(0);
                    int limit = paeaTaskLimitPara.getLimit();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    Date correctLimitDate =paeaErError.getCorrectLimitDate() ;
                    //Date correctLimitDate = CommonUtil.getSpecialWorkDate(erError.getCreateTime(), limit);
                    Date nowDate = new Date(System.currentTimeMillis());
                    int correctLimitDateStr = Integer.parseInt(sdf.format(correctLimitDate));
                    int nowDateStr = Integer.parseInt(sdf.format(nowDate));
                    int compareValue = nowDateStr-correctLimitDateStr;
                    // 在限期整改日期内回复
                    if (compareValue <= 0) {
                        paeaErError.setReplyFlag(PaeaErrorReplyStatus.已回复.getValue());
                        paeaErError.setCorrectOvertime(0);
                    } else {// 超出整改日期回复
                        paeaErError.setReplyFlag(PaeaErrorReplyStatus.超期已回复.getValue());
                        paeaErError.setCorrectOvertime(1);
                    }
                    this.saveOrUpdate(paeaErError);
                }
                //差错整改日期以下发到网点日期开始计算XQ.XU 20171123
                //TODO 差错整改日期
                if (PaeaUserRole.is监管主管(roleCode) && (paeaErError.getReplyFlag() ==null || paeaErError.getReplyFlag()==PaeaErrorReplyStatus.未回复.getValue())) {
                    //paeaErError.setCorrectLimitDate(DateTimeUtil.parseDate_FMT_YY_MM_DD(CommonParaTool.getCorrectLimitDate()));
                }
            }
        }
}
